"use client";
import { Link } from "@heroui/link";
import { Snippet } from "@heroui/snippet";
import { Code } from "@heroui/code";
import { button as buttonStyles } from "@heroui/theme";
import { motion } from "framer-motion";
import { siteConfig } from "@/config/site";
import { title, subtitle } from "@/components/primitives";
import { GithubIcon } from "@/components/icons";
import { Alert } from "@heroui/alert";
import { useState, useEffect } from "react";
import { Card, CardBody } from "@heroui/card";
import {Textarea} from "@heroui/input";
import { io, Socket } from "socket.io-client";

let socket: Socket;

export default function Home() {
  const [isConnected, setIsConnected] = useState(false);
  const [messages, setMessages] = useState<{ user: string; message: string }[]>(
    [],
  );

  const [inputMessage, setInputMessage] = useState<string>("");

  useEffect(() => {
    socket = io("http://localhost:4000");
    socket.on("connect", () => {
      console.log("Connected to the socket.io server");
      setIsConnected(true);

      socket.on("message", (messages) => {
        setMessages((prevMessages) => {
          return [...prevMessages, JSON.parse(messages)];
        });
      });
    });
    socket.on("disconnect",() => {
      console.log("Disconnected from the socket.io server");
      setIsConnected(false);
  })
  
  }, []);

  const handleSendMessage = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      socket.emit("message", inputMessage);
      setMessages((prevMessages) => {
        return [
          ...prevMessages,
          {
            user: "Me",
            message: inputMessage,
          },
        ];
      });
      setInputMessage("");
    }
  };
  return (
    <div className="min-h-screen bg-slate-300 flex flex-col">
      <div className="z-50 h-10 sticky top-0">
        {isConnected ? (
          <Alert className="text-xs " color="success" title="成功连接" />
        ) : (
          <Alert className="text-xs " color="danger" title="连接中" />
        )}
      </div>
      <h1 className="text-center text-3xl font-bold py-8">Simple Chat Room</h1>

      <div className="flex-1 p-4 ">
        <ul>
          {messages.map((message, index) => (
            <li key={index}>
              <Card className={`max-w-xs mb-2 ${message.user === 'Me' ? 'ml-auto bg-blue-300':''}`} radius="md" shadow="sm">
                <CardBody>
                  <div className="text-sm text-gray-800">{message.message}</div>
                  <div className="text-xs text-gray-400 mt-1 text-right">
                    {message.user}
                  </div>
                </CardBody>
              </Card>
            </li>
          ))}
        </ul>
      </div>

      <div className="p-4 sticky bottom-0 w-full">
        <Textarea
          isRequired
          type="text"
          variant="underlined"
          className="bg-white text-xl rounded px-2 py-2 shadow w-full outline-none focus:ring-2 ring-slate-500"
          isDisabled = {!isConnected}
          value={inputMessage}
          onChange={(e) => {
            setInputMessage(e.target.value);
          }}
          onKeyDown={handleSendMessage}
        />
      </div>


    </div>
  );
}
